#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils


def get_plugin_info():
    plugin_info = {
        "name": "centos_authentication_003 Blank_password_account",
        "plugin_id": "centos_authentication_003",
        "plugin_type": "Authentication",
        "info": "Find the blank password account",
        "level": "C",
        "module": "Safety reinforcement",
        "author": "fanyi",
        "keyword": "Safety reinforcement",
        "configable": "false",
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


# 扫描函数
def scan(ip, sys_user, sys_pwd, flag=0):
    des_list = []
    error_count = 0
    logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Start.")
    # 获取空口令账户
    cmd = "awk -F: \'length($2)==0 {printf $1\"\\t\"}\' /etc/shadow"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    # 检错，每次执行命令都会进行检错，并决定返回退出/继续执行
    if not result and len(output) != 0:
        # 空口令账户警告
        account_des = "Found Account with EMPTY Password!"
        error_count += 1
        des_list.append(account_des)
        logger.debug_warning(cur_user, cur_module, cur_task+'_Scan', '', account_des)
        # 返回值格式化，去除不需要的内容/符号
        output = output[0].split()
        cou = 0
        user_list = "username:"
        while cou < len(output):
            user_list = user_list + " " + output[cou]
            cou += 1
        des_list.append(user_list.encode('utf8'))
        logger.debug_warning(cur_user, cur_module, cur_task+'_Scan', '', user_list.encode('utf8'))
    elif not result and len(output) == 0:
        account_des = "All account are Safe."
        des_list.append(account_des)
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', account_des)
        des_list.append("Scan Complete.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Complete.")
        return des_list, error_count
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
        error_count += 1
        return des_list, error_count
    des_list.append("Scan Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Complete.")
    if flag == 1:
        reinforce_des, reinforce_err = reinforce(ip, sys_user, sys_pwd)
        des_list.extend(reinforce_des)
    return des_list, error_count


# 加固函数
def reinforce(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    des_list.append("Please add password to the account.")
    des_list.append("Reinforce Complete.")
    return des_list, error_count


# 回滚函数
def rollback(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    des = "This function don't need to rollback."
    des_list.append(des)
    return des_list, error_count


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        des_list = []
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', "centos_authentication_003 Start")
        if comm == 1:
            des_scan, error_scan = scan(ip, sys_user, sys_pwd, flag=0)
            des_list.extend(des_scan)
            step_error = int(error_scan)
        elif comm == 2:
            des_reinforce, error_reinforce = scan(ip, sys_user, sys_pwd, flag=1)
            des_list.extend(des_reinforce)
            step_error = int(error_reinforce)
        elif comm == 3:
            des_rollback, error_rollback = rollback(ip, sys_user, sys_pwd)
            des_list.extend(des_rollback)
            step_error = int(error_rollback)
        else:
            return {"code": 3, "count": 0, "des": ['command must be 1/2/3']}
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', "centos_authentication_003 Complete")
        if step_error == 0:
            code = 0
        elif step_error <= -1:
            code = 2
        else:
            code = 1
        return {"code": code, "count": step_error, "des": des_list}
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        logger.debug_error(cur_user, cur_module, cur_task+'_Check', '', des)
        return {"code": code, "count": 0, "des": des}


#check(ip="100.2.91.150", system_user="root", system_pwd="admin", command=0, flag=0)
